IIFE, Destructuring and Spread Operator in JS
In this article, we will learn about three main topics of JavaScript which is necessary to learn and master IIFE(Immediately Invokede Function Expression), Destructuring and Spread Operator. If you like this article make sure to react below and also watch the Youtbe Video by just clicking on the thumbnail.
What is an IIFE?
An IIFE is a function in JavaScript is defined and runs immediately after itโs created.
Example of IIFE
(function() {
console.log("I run immediately!");
})();
Destructuring Assignment
Itโs a way to unpack values from arrays or objects into separate variables.
Example with arrays:-
let fruits = ["apple", "banana", "mango"];
// Destructuring
let [first, second] = fruits;
console.log(first); // "apple"
console.log(second); // "banana"
Instead of fruits[0] or fruits[1], we directly assign them.
Example with Objects:-
let person = { name: "Alice", age: 25, city: "New York" };
// Destructuring
let { name, age } = person;
console.log(name); // "Alice"
console.log(age); // 25
It pulls out name and age directly from the object.
Spread Operator (...)
It expands (spreads) elements of an array or object into individual items.
Example with arrays:-
let numbers = [1, 2, 3];
let moreNumbers = [...numbers, 4, 5];
console.log(moreNumbers); // [1, 2, 3, 4, 5]
Copies all values of numbers into moreNumbers.
Example with Objects:-
let user = { name: "Alice", age: 25 };
let updatedUser = { ...user, city: "London" };
console.log(updatedUser);
// { name: "Alice", age: 25, city: "London" }
It copies properties from one object and adds new ones.